import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import AntdDatePicker from '@/components/AntdDatePicker';
import AntdInput from '@/components/AntdInput';
import { columnsDriver } from '@/pages/Common/common';
import {  allUrl,allDispatchType, } from './utils';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';

import { Row,Col,Card,  Form,  Input,  Select, Radio, Collapse,  DatePicker,  AutoComplete,  Button,} from 'antd';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import { allDictList } from '@/utils/constans';
import styles from '@/pages/Operate.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormatH = 'YYYY-MM-DD HH:mm:ss';
const dateFormat = 'YYYY-MM-DD';
@connect(({ Endorse,tmsOil, common, loading, list }) => ({
  tmsOil,
  Endorse,
  endorseList:Endorse.endorseList,
  endorseDetail:Endorse.endorseDetail,
  list,
  dictObject: common.dictObject,
  // id: tmsOil.id,
  loading: loading.models.tmsOil,
}))
@Form.create()
class addEndorse extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      beAssume:'',
      beWork:'',
      processMode:'',
      cars: [],
      drivers:[],
      // trafficOffenceTime:'',
      trafficOffenceAddress:'',
      trafficOffenceProject:'',
      deleteFileIds: [],

      forfeit :'',
      scoring:0,
      lawEnforcement:'',
      handlingInformation:'',
      handlingDate:'',

      visible: false,
      
      activeKey: ['1', '2'],
  
      disabled: false,
      
    };
    this.fileList = [];
  }
  componentDidMount() {
   
    const { match, dispatch ,dictObject} = this.props;

    const ID = match ? match.params.id : '';
    if (ID) {
      this.getSelectDetails(ID);
      this.queryFileList(ID);
      
    } else {
      this.props.form.resetFields();
    }

    //字典：
    const allDict = [allDictList.currencyType, allDictList.saleCompany, allDictList.oilType,];
    allDict.map(v => {
      dispatch({
        type: 'common/querytDictByCode',
        payload: { code: v },
      });
    });
  }
  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'ENDORSEMENT' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  // 表格 数据变化
  changeHundredConsump = (value, type) => {
    
    this.setState(
      {
        [type]: value,
      },
     
    );
  };

  //详情信息：
  getSelectDetails = ID => {
    const { dispatch } = this.props;
    dispatch({
      type: 'Endorse/selectEndorseDetail',
      payload: { id: ID },
      callback: data => {
        if (!data) return;
        const {
          beAssume,
          beWork,
          driverId,
          driverName,
          forfeit,
          handlingDate,
          handlingInformation,
          lawEnforcement,
          processMode,
          scoring,
          trafficOffenceAddress,
          trafficOffenceProject,
          trafficOffenceTime,
          vehicleId,
          vehicleName,
        } = data;
        
        const unitPrice = forfeit && Number(forfeit) !== 0 ? Number(forfeit).toFixed(2) : 0;
        this.setState(
          {
            cars: [{ id:vehicleId }],
            drivers:[{id:driverId}],
            beAssume,
            beWork,
            processMode,

            forfeit,
            handlingDate,
            handlingInformation,
            lawEnforcement,
            scoring,
            trafficOffenceAddress,
            trafficOffenceProject,
            trafficOffenceTime,
           
          },
          
        );
        // this.setFileList(data.attachments);
        // this.props.form.setFieldsValue({ price: unitPrice });
      },
    });
  };
  getSelectList = (type, val) => {
    const { dispatch } = this.props;
    let params = {};
    if (type == 'search') {
      params = val;
    }
    params.currentPage = 1;
    dispatch({
      type: 'Endorse/selectEndorseList',
      payload: params,
    });
  };

  //保存 基本信息：
  saveBasicInfo = e => {
    e.stopPropagation();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      let { trafficOffenceTime,handlingDate,driverId,fileTokens,...value} = values;
      //附件
      value.fileTokens = filterAddFile(fileTokens);
      value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
       //时间：
      //  console.log('trafficOffenceTime------',trafficOffenceTime);
       
       value.trafficOffenceTime = trafficOffenceTime ? moment(trafficOffenceTime).format(dateFormatH) : '';
       value.handlingDate = handlingDate ? moment(handlingDate).format(dateFormat) : '';
      //编辑时传入id
      const {
        match: { params },
        dispatch,
        dictObject,
       
      } = this.props;
      
     value.driverName=driverId[0].name
     value.driverId=driverId[0].id
      
    //  let AA= dictObject[allDictList.traffic_offence]
    //  let _AA=AA.filter(v=>v.code==value.trafficOffenceProjectCode)

    // value.trafficOffenceProject= _AA[0].value
    
     value.vehicleName=this.state.cars[0].cartPlateOneNo
     value.vehicleId=this.state.cars[0].id
    
    const { id } = this.props;

     if (params.id) {
      value.id = params.id || id;
      dispatch({
        type: allDispatchType.operate,
        payload: value,
        callback: () => {
          
          this.setState(preState => ({
            
            disabled: !preState.disabled,
          }),()=>console.log('disabled',this.state.disabled));
          this.getSelectList();
          this.queryFileList(params.id||id);


        },
      });
    }else{
      dispatch({
        type: allDispatchType.operate,
        payload: value,
        callback: res => {
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
          this.queryFileList(res||id);

          dispatch({
            type: allDispatchType.detail,
            payload: { id: res },
            callback: data => {
              // data.attachments && this.setFileList(data.attachments);
              // this.setState({ 
              //   cars: [{ id: data.vehicleId,name:data.vehicleName }],
              //  });
               if (data) {
                    dispatch({
                      type: 'common/setTabsName',
                      payload: {
                        id: res,
                        // name: data.upkeepNo,
                        name:res,
                        isReplaceTab: true,
                      },
                      callback: result => {
                        if (result) {
                          router.push(`/carDaily/EndorseList/editEndorse/${res}`);
                        }
                      },
                  })
                }
            },
          });
          this.getSelectList();
        },
      });
    }

     
    });
  };

  render() {
    let { disabled, cars } = this.state;
    const {
      endorseList, endorseDetail ,
      list: { carList },
      form: { getFieldDecorator },
      dictObject,
      match: { params },
    } = this.props;
    const currentId = params.id;
    const details = endorseDetail[currentId] ? endorseDetail[currentId] : {};
    console.log('details-----',details,Boolean(details))

    const vehicleList = [];
    if(disabled===false){
       disabled= details.status=='SUBMITTED'
    }
    
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{details && currentId ? details.oilNo : '新增违章'}</span>
           
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={details && currentId ? codes.edit : codes.add}
          />
        ) : (
            <Button.Group>
              <AdButton
                type="primary"
                onClick={e => this.saveBasicInfo(e)}
                text="保存"
                code={details && currentId ? codes.edit : codes.add}
              />
              {details && currentId && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                  code={details && currentId ? codes.edit : codes.add}
                />
              )}
            </Button.Group>
          )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue: details && details.currencyType ? details.currencyType : 'CNY',
    })(
      <Select placeholder="请选择" style={{ width: 90 }} disabled={disabled}>
        {dictObject[allDictList.currencyType] &&
          dictObject[allDictList.currencyType].map(item => (
            <Option key={item.code}>{item.value}</Option>
          ))}
      </Select>
    );
    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={this.props.type == 'add' ? '违章新建' : genExtraBasicInfo()}>
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="违章详情" key="2" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="车辆">
                        {getFieldDecorator('vehicleId', {
                          rules: [{ required: true}],
                          initialValue: details.vehicleId ? details.vehicleId : '',
                        })(
                          // this.Complete(dictObject[allDictList.saleCompany])

                          <SearchSelect
                            
                            dataUrl="tms/tms-vehicle/selectListByArchives"
                            url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={cars} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={e => this.changeHundredConsump(e, 'cars')} // 获取选中值
                            scrollX={480}
                            id="ArchivesList_1"
                            allowClear={true}
                            // payload={{ categoryList: ['HEADSTOCK', 'CARLOAD'] }} //筛选为整车和车头的
                            disabled={disabled}
                        />
                        
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="司机">
                        {getFieldDecorator('driverId', {
                          rules: [{ required: true, message: '请选择司机' }],
                          initialValue: details.driverId ? details.driverId : '',
                        })(
                          <SearchSelect
                            multiple={false} // 是否多选
                            dataUrl={allUrl.driverList}
                            url={allUrl.driverDetail}
                            selectedData={this.state.drivers} // 选中值
                            columns={columnsDriver} // 表格展示列
                            onChange={e => this.changeHundredConsump(e, 'driverName')} // 获取选中值
                            id="driverPaper_operate_1"
                            scrollX={500}
                            disabled={disabled}
                            // payload={{ categoryList: ['HEADSTOCK', 'CARLOAD'],ownCompanyId:"JS02" }} 
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="是否在职">
                        {getFieldDecorator('beWork', {
                          rules: [{ required: true}],
                          initialValue: details.beWork ? details.beWork : "ONTHEJOB",
                        })(
                          <Radio.Group
                            // disabled={checkId ? true : false}
                            >
                                <Radio value="DIMISSION" disabled={disabled}>否</Radio>
                                <Radio value="ONTHEJOB" disabled={disabled}>是</Radio>
                            </Radio.Group>
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="交通违法时间">
                        {getFieldDecorator('trafficOffenceTime', {
                          rules: [{ required: true}],
                          initialValue:
                            details && details.trafficOffenceTime 
                              ? moment(details.trafficOffenceTime , dateFormatH)
                              : undefined,
                        })(
                          <AntdDatePicker 
                            disabled={disabled}
                            showTime={true}
                            onChange={e => this.changeHundredConsump(e, 'trafficOffenceTime')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="交通违法地点">
                        {getFieldDecorator('trafficOffenceAddress', {
                          rules: [{ required: true}],
                          initialValue: details.trafficOffenceAddress ? details.trafficOffenceAddress : undefined,
                        })(
                          <AntdInput style={{backgroundColor:'#ffffff'}}
                            // mode="money"
                            disabled={disabled}
                            // mode="anyNumber"
                            placeholder="请输入交通违法地点"
                            onChange={e => this.changeHundredConsump(e, 'trafficOffenceAddress')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="交通违法项目">
                        {getFieldDecorator('trafficOffenceProject', {
                          rules: [{ required: true }],
                          initialValue: details.trafficOffenceProject ? details.trafficOffenceProject : undefined,
                        })(
                          // <Select
                          //   disabled={disabled}
                          //   placeholder="请选择"
                          //   // onSelect={this.oilCardTypeSelectd}
                          //   onChange={(value, options) => this.changeHundredConsump(value, 'trafficOffenceProjectCode')}
                          // >
                          //   {dictObject[allDictList.traffic_offence] &&
                          //     dictObject[allDictList.traffic_offence].map(item => (
                          //       <Option key={item.code}>{item.value}</Option>
                          //     ))}
                          // </Select>
                          <AntdInput 
                            // mode="money"
                            disabled={disabled}
                            // mode="anyNumber"
                            placeholder="请输入交通违法项目"
                            onChange={e => this.changeHundredConsump(e, 'trafficOffenceProject')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="罚款">
                        {getFieldDecorator('forfeit', {
                          rules: [{ required: true }],
                          initialValue: details.forfeit  ? details.forfeit : undefined,
                        })(
                          <AntdInput
                            // mode="money"
                            disabled={disabled}
                            mode="money"
                            placeholder="请输入罚款金额"
                            onChange={e => this.changeHundredConsump(e, 'forfeit')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="处理方式">
                        {getFieldDecorator('processMode', {
                          rules: [{ required: true, message: '请输入加油时间' }],
                          initialValue: details.processMode ? details.processMode : "WARNING",
                        })(
                          <Radio.Group
                            // disabled={checkId ? true : false}
                            >
                                <Radio value="FORFEIT" disabled={disabled}>罚款</Radio>
                                <Radio value="WARNING" disabled={disabled}>警告</Radio>
                            </Radio.Group>
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="计分">
                        {getFieldDecorator('scoring', {
                          rules: [{ required: true }],

                          // rules: [
                          //   {
                          //     required: _oilCardType === 'CARD' ? true : false,
                          //     message: '请输入油卡号',
                          //   },
                         // ],
                          initialValue: details.scoring ? details.scoring : undefined,
                        })(
                          <AntdInput
                            // mode="money"
                            disabled={disabled}
                            mode="scoring"
                            placeholder="请输入违章记分"
                            onChange={e => this.changeHundredConsump(e, 'scoring')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="执法单位">
                        {getFieldDecorator('lawEnforcement', {
                          rules: [{ required: true, message: '请输入加油时间' }],
                          initialValue:
                            details.lawEnforcement ? details.lawEnforcement:undefined
                              
                        })(
                          <AntdInput
                          // mode="money"
                          disabled={disabled}
                          // mode="anyNumber"
                          placeholder="请填写执法单位"
                          onChange={e => this.changeHundredConsump(e, 'lawEnforcement')}
                        />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="处理情况">
                        {getFieldDecorator('handlingInformation', {
                          rules: [{ required: false, message: '请输入处理情况' }],
                         
                          initialValue: details.handlingInformation ? details.handlingInformation : 'FINISHED',
                        })(
                          <Radio.Group
                            // disabled={checkId ? true : false}
                            >
                                <Radio value="UNFINISHED" disabled={disabled}>未完成</Radio>
                                <Radio value="FINISHED" disabled={disabled}>完成</Radio>
                          </Radio.Group>
                          
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="处理日期">
                        {getFieldDecorator('handlingDate', {
                          rules: [{ required: false, message: '请输入处理时间' }],
                          initialValue:
                            details&& details.handlingDate
                              ? moment(details.handlingDate, dateFormat)
                              : undefined,
                        })(
                          <AntdDatePicker
                          disabled={disabled}
                          onChange={e => this.changeHundredConsump(e, 'handlingDate')}
                        />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="是否公司承担">
                        {getFieldDecorator('beAssume', {
                          rules: [{ required: true, message: '请输入加油时间' }],
                          
                          initialValue: details.beAssume ? details.beAssume : "ASSUME",
                        })(
                          <Radio.Group
                            // disabled={checkId ? true : false}
                            >
                                <Radio value="NOTASSUME" disabled={disabled}>不承担</Radio>
                                <Radio value="ASSUME" disabled={disabled}>承担</Radio>
                            </Radio.Group>
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                          <Form.Item label="附件">
                            {getFieldDecorator('fileTokens',{
                               rules: [{ required: true, message: '请输入加油时间' }],
                          
                            })(
                              <FileReader disabled={disabled} urlType="tms" />
                            )}
                          </Form.Item>
                        </Col>
                   
                  </Row>
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
export default addEndorse;
